<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.name" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入试卷名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">出卷</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="paperName" label="试卷名称" />
        <el-table-column prop="courseName" label="课程名称" />
        <el-table-column prop="teacherName" label="授课教师" />
        <el-table-column prop="type" label="试卷类型">
          <template v-slot="scope">
            <el-tag v-if="scope.row.examType === '手动选题'" type="success">{{ scope.row.examType }}</el-tag>
            <el-tag v-if="scope.row.examType === '自动组卷'" type="primary">{{ scope.row.examType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDatetime" label="开始时间" />
        <el-table-column prop="endDatetime" label="结束时间" />
        <el-table-column prop="durationMinutes" label="小测时长">
          <template v-slot="scope">
            {{ scope.row.durationMinutes }} 分钟
          </template>
        </el-table-column>
        <el-table-column prop="status" label="小测状态">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === '进行中'" type="primary">{{ scope.row.status }}</el-tag>
            <el-tag v-if="scope.row.status === '未开始'" type="warning">{{ scope.row.status }}</el-tag>
            <el-tag v-if="scope.row.status === '已结束'" type="danger">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <el-dialog title="试卷信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" :rules="formRules" label-width="70px" style="padding: 20px">
        <el-form-item prop="courseId" label="选择课程">
          <el-select v-model="data.form.courseId" placeholder="请选择课程" @change="loadQuestion">
            <el-option
                v-for="item in data.courseData"
                :key="item.id"
                :label="item.courseName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="paperName" label="试卷名称">
          <el-input v-model="data.form.paperName" placeholder="请输入试卷名称"></el-input>
        </el-form-item>
        <el-form-item prop="startDatetime" label="开始时间">
          <el-date-picker
              style="width: 100%"
              v-model="data.form.startDatetime"
              type="datetime"
          placeholder="请选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item prop="endDatetime" label="结束时间">
          <el-date-picker
              style="width: 100%"
              v-model="data.form.endDatetime"
              type="datetime"
          placeholder="请选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item prop="durationMinutes" label="小测时长">
          <el-input v-model="data.form.durationMinutes" placeholder="请输入小测时长（分钟）"></el-input>
        </el-form-item>
        <el-form-item prop="passingScore" label="及格分数" :label-width="'100px'">
          <el-slider
              v-model="data.form.passingScore"
              :min="0"
              :max="100"
              :step="1"
              show-tooltip
              :format-tooltip="(val) => `${val}%`"
              label="及格分数（%）"
          />
          <el-input
              v-model="data.form.passingScore"
              style="width: 120px; margin-top: 10px;"
              placeholder="请输入及格百分比"
              :max="100"
              :min="0"
              :type="'number'"
              @blur="validatePercentage"
          >
            <template #append>%</template>
          </el-input>
        </el-form-item>


        <el-form-item prop="examType" label="出题方式">
          <el-select v-model="data.form.examType" placeholder="请选择出题方式">
            <el-option label="手动选题" value="手动选题"></el-option>
            <el-option label="自动组卷" value="自动组卷"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="questionIds" label="选择题目" v-if="data.form.examType === '手动选题'">
          <el-select
              v-model="data.form.questionIds"
              multiple
              placeholder="请选择题目"
              style="width: 100%"
          >
            <el-option
                v-for="item in data.questionData"
                :key="item.id"
                :label="item.questionStem + '（' + item.typeName + '）'"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 根据题目类型动态生成题目个数 -->
        <div v-if="data.form.examType === '自动组卷'">
          <el-form-item
              v-for="(questionType, index) in data.questionTypes"
              :key="questionType.id"
              :prop="'autoGenQustion.' + index + '.count'"
              :label="questionType.typeName"
          >
            <el-input-number
                v-model.number="data.form.autoGenQustion[index].count"
                :min="0"
                placeholder="请输入题目数量"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import {reactive,ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";
const validatePercentage = () => {
  const passingScore = data.form.passingScore;
  if (passingScore < 0 || passingScore > 100) {
    ElMessage.error('请输入0到100之间的百分比');
    data.form.passingScore = Math.max(0, Math.min(passingScore, 100)); // 限制为0到100之间
  }
};
// 表单验证规则
const formRules = {
  paperName: [{ required: true, message: '试卷名称不能为空', trigger: 'blur' }],
  courseId: [{ required: true, message: '课程不能为空', trigger: 'change' }],
  startDatetime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  endDatetime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  durationMinutes: [{ required: true, message: '小测时长不能为空', trigger: 'blur' }],
  passingScore: [{ required: true, message: '及格分数不能为空', trigger: 'blur' }],
  examType: [{ required: true, message: '请选择出题方式', trigger: 'change' }],
  // 题目验证规则
  questionIds: [
    {
      required: true,
      message: '请选择题目',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (data.form.examType === '手动选题' && (!value || value.length === 0)) {
          callback(new Error('请选择题目'));
        } else {
          callback();
        }
      }
    }
  ],
  'autoGenQustion': {
    type: 'array',
    required: true,
    message: '至少选择一个题目类型',
    validator: (rule, value, callback) => {
      const hasCount = value.some(item => item.count > 0);
      if (!hasCount) {
        callback(new Error('至少选择一个题目类型'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }
}

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  formVisible: false,
  form: {
    autoGenQustion:[]
  },
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  paperName: null,
  ids: [],
  courseData: [],
  questionData: [],
  questionTypes: []  // 用于存储题目类型
})
const loadQuestionType = () => {
  request.get('/questionType/selectAll', {
  }).then(res => {
    if (res.code === '200') {
      data.questionTypes = res.data;
      // 初始化 autoGenQustion 数组
      data.form.autoGenQustion = data.questionTypes.map(questionType => ({
        id: questionType.id,
        count: 0
      }));
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const loadCourse = () => {
  request.get('/course/selectAll', {
    params: {
      teacherId: data.user.id
    }
  }).then(res => {
    if (res.code === '200') {
      data.courseData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const loadQuestion = (courseId) => {
  request.get('/question/selectAll', {
    params: {
      courseId: courseId
    }
  }).then(res => {
    if (res.code === '200') {
      data.questionData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const load = () => {
  request.get('/testPaper/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      paperName: data.paperName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || []
      data.total = res.data?.total
    }
  })
}
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
  loadQuestionType();
}
const form = ref(null);
const add = () => {
  console.log(data.form);
  form.value.validate((valid) => {
    if (valid) {
      console.log(data.form);
      request.post('/testPaper/add', data.form).then(res => {
        if (res.code === '200') {
          ElMessage.success('操作成功');
          data.formVisible = false;
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      ElMessage.error('表单数据有误，请检查后重新提交');
    }
  });
};

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/testPaper/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete("/testPaper/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

const reset = () => {
  data.paperName = null
  load()
}

load()
loadCourse()
loadQuestionType();
</script>
